const app = getApp()

Page({
  data: {
    productId: null,
    storeId: null,
    reviews: [],
    statistics: {
      totalCount: 0,
      avgRating: 0,
      goodRate: 0,
      normalRate: 0,
      badRate: 0,
      hasImageCount: 0
    },
    loading: false,
    loadingMore: false,
    hasMore: true,
    currentPage: 0,
    pageSize: 10,
    filter: {
      rating: 0, // 0:全部, 1-5:对应星级
      hasImage: false, // 是否只看有图
      tag: '' // 筛选标签
    },
    product: {}, // 商品信息
    store: {} // 商店信息
  },

  onLoad(options) {
    const { productId, storeId, type = 'product' } = options
    
    if (type === 'product' && !productId) {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }

    if (type === 'store' && !storeId) {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }
    
    this.setData({
      productId: productId ? parseInt(productId) : null,
      storeId: storeId ? parseInt(storeId) : null,
      type
    })
    
    // 加载商品或店铺信息
    if (type === 'product') {
      this.loadProductInfo()
    } else {
      this.loadStoreInfo()
    }
    
    // 加载评价统计数据
    this.loadStatistics()
    
    // 加载评价列表
    this.loadReviews()
  },

  // 加载商品信息
  loadProductInfo() {
    wx.request({
      url: `${app.globalData.apiBaseUrl}/api/products/${this.data.productId}`,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          this.setData({
            product: res.data.data
          })
          // 设置页面标题
          wx.setNavigationBarTitle({
            title: '商品评价'
          })
        }
      }
    })
  },

  // 加载店铺信息
  loadStoreInfo() {
    wx.request({
      url: `${app.globalData.apiBaseUrl}/api/stores/${this.data.storeId}`,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          this.setData({
            store: res.data.data
          })
          // 设置页面标题
          wx.setNavigationBarTitle({
            title: '店铺评价'
          })
        }
      }
    })
  },

  // 加载评价统计
  loadStatistics() {
    const { type, productId, storeId } = this.data
    const url = type === 'product' 
      ? `${app.globalData.apiBaseUrl}/api/reviews/statistics/product/${productId}`
      : `${app.globalData.apiBaseUrl}/api/reviews/statistics/store/${storeId}`
    
    wx.request({
      url,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          this.setData({
            statistics: res.data.data
          })
        }
      }
    })
  },

  // 加载评价列表
  loadReviews(reset = true) {
    const { productId, storeId, type, currentPage, pageSize, filter } = this.data
    
    if (reset) {
      this.setData({
        loading: true,
        currentPage: 0,
        hasMore: true
      })
    } else {
      this.setData({
        loadingMore: true
      })
    }

    // 构建API URL
    let url
    if (type === 'product') {
      url = `${app.globalData.apiBaseUrl}/api/reviews/product/${productId}?page=${reset ? 0 : currentPage}&size=${pageSize}`
    } else {
      url = `${app.globalData.apiBaseUrl}/api/reviews/store/${storeId}?page=${reset ? 0 : currentPage}&size=${pageSize}`
    }

    // 添加筛选条件
    if (filter.rating > 0) {
      url += `&minRating=${filter.rating}&maxRating=${filter.rating}`
    }
    
    if (filter.hasImage) {
      url += '&hasImage=true'
    }
    
    if (filter.tag) {
      url += `&tag=${filter.tag}`
    }
    
    wx.request({
      url,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          const { list, total, hasNext } = res.data.data
          
          // 处理评价数据
          const processedList = this.processReviewsList(list)
          
          this.setData({
            reviews: reset ? processedList : [...this.data.reviews, ...processedList],
            currentPage: reset ? 1 : currentPage + 1,
            hasMore: hasNext
          })
        } else {
          wx.showToast({
            title: '加载评价失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      },
      complete: () => {
        this.setData({
          loading: false,
          loadingMore: false
        })
        
        // 停止下拉刷新
        wx.stopPullDownRefresh()
      }
    })
  },

  // 处理评价列表数据
  processReviewsList(list) {
    return list.map(review => {
      // 解析图片和标签JSON
      try {
        if (review.images && typeof review.images === 'string') {
          review.imagesList = JSON.parse(review.images)
        } else {
          review.imagesList = []
        }
        
        if (review.tags && typeof review.tags === 'string') {
          review.tagsList = JSON.parse(review.tags)
        } else {
          review.tagsList = []
        }
      } catch (err) {
        console.error('解析评价数据错误', err)
        review.imagesList = []
        review.tagsList = []
      }
      
      // 格式化日期
      if (review.createdAt) {
        const date = new Date(review.createdAt)
        review.formattedDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
      }
      
      return review
    })
  },

  // 切换筛选条件
  changeFilter(e) {
    const { type, value } = e.currentTarget.dataset
    const filter = { ...this.data.filter }
    
    if (type === 'rating') {
      filter.rating = parseInt(value)
    } else if (type === 'hasImage') {
      filter.hasImage = !filter.hasImage
    } else if (type === 'tag') {
      filter.tag = value
    }
    
    this.setData({ filter })
    this.loadReviews()
  },

  // 点赞评价
  likeReview(e) {
    const { id, index } = e.currentTarget.dataset
    
    wx.request({
      url: `${app.globalData.apiBaseUrl}/api/reviews/${id}/like`,
      method: 'POST',
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          // 更新点赞数
          const reviews = [...this.data.reviews]
          reviews[index].likes += 1
          this.setData({ reviews })
          
          wx.showToast({
            title: '点赞成功',
            icon: 'success'
          })
        }
      }
    })
  },

  // 预览图片
  previewImage(e) {
    const { url, urls } = e.currentTarget.dataset
    wx.previewImage({
      current: url,
      urls: urls
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadStatistics()
    this.loadReviews()
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loadingMore) {
      this.loadReviews(false)
    }
  }
}) 